<template>
  <div class="chart-container">
    <!-- 筛选项 -->
    <div class="filters-container">
      <h3 class="section-title">数据筛选</h3>
      <div class="filters-grid">
        <el-date-picker
          v-model="filters.startTime"
          type="datetime"
          placeholder="选择开始时间"
          class="filter-item"
          clearable
        />

        <el-date-picker
          v-model="filters.endTime"
          type="datetime"
          placeholder="选择结束时间"
          class="filter-item"
          clearable
        />

        <el-input
          v-model="filters.houseId"
          placeholder="输入家庭ID"
          class="filter-item"
          clearable
        />

        <el-button
          type="primary"
          @click="fetchChartData"
          class="filter-btn"
          :icon="Search"
          :loading="loading"
        >
          筛选
        </el-button>
      </div>
    </div>

    <!-- 图表容器 -->
    <div class="charts-wrapper">
      <!-- 收入和支出总额饼图 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3 class="chart-title">收入与支出总额</h3>
        </div>
        <div class="chart-content">
          <div v-if="isEmptyData" class="empty-tips">
            <el-empty description="暂无数据" />
          </div>
          <div v-else id="total-chart" ref="totalChartRef" style="width: 100%; height: 100%;"></div>
        </div>
      </div>

      <!-- 收入方式饼图 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3 class="chart-title">收入方式</h3>
        </div>
        <div class="chart-content">
          <div v-if="isEmptyData" class="empty-tips">
            <el-empty description="暂无数据" />
          </div>
          <div v-else id="income-way-chart" ref="incomeWayChartRef" style="width: 100%; height: 100%;"></div>
        </div>
      </div>

      <!-- 支出方式饼图 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3 class="chart-title">支出方式</h3>
        </div>
        <div class="chart-content">
          <div v-if="isEmptyData" class="empty-tips">
            <el-empty description="暂无数据" />
          </div>
          <div v-else id="outcome-way-chart" ref="outcomeWayChartRef" style="width: 100%; height: 100%;"></div>
        </div>
      </div>

      <!-- 支出分类饼图 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3 class="chart-title">支出分类</h3>
        </div>
        <div class="chart-content">
          <div v-if="isEmptyData" class="empty-tips">
            <el-empty description="暂无数据" />
          </div>
          <div v-else id="outcome-category-chart" ref="outcomeCategoryChartRef" style="width: 100%; height: 100%;"></div>
        </div>
      </div>

      <!-- 收入分类饼图 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3 class="chart-title">收入分类</h3>
        </div>
        <div class="chart-content">
          <div v-if="isEmptyData" class="empty-tips">
            <el-empty description="暂无数据" />
          </div>
          <div v-else id="income-category-chart" ref="incomeCategoryChartRef" style="width: 100%; height: 100%;"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { Search } from '@element-plus/icons-vue'
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import { homeShow } from '@/api/home'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 数据状态
const chartData = ref({
  total: { income: 0, outcome: 0 },
  incomeWay: [],
  outcomeWay: [],
  outcomeCategory: [],
  incomeCategory: []
})
const filters = ref({
  startTime: null,
  endTime: null,
  houseId: null
})
const loading = ref(false)
const isEmptyData = ref(false)

// 图表实例
const totalChartRef = ref(null)
const incomeWayChartRef = ref(null)
const outcomeWayChartRef = ref(null)
const outcomeCategoryChartRef = ref(null)
const incomeCategoryChartRef = ref(null)

const totalChartInstance = ref(null)
const incomeWayChartInstance = ref(null)
const outcomeWayChartInstance = ref(null)
const outcomeCategoryChartInstance = ref(null)
const incomeCategoryChartInstance = ref(null)

// 登录检查
const checkLoginStatus = () => {
  if (!localStorage.getItem('Authorization')) {
    router.push('/login')
  }
}

// 初始化/更新图表
const initTotalChart = () => {
  if (!totalChartRef.value) return

  if (totalChartInstance.value) {
    totalChartInstance.value.dispose()
  }

  totalChartInstance.value = echarts.init(totalChartRef.value)

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['收入', '支出']
    },
    series: [
      {
        name: '总额',
        type: 'pie',
        radius: '50%',
        data: [
          { value: chartData.value.total.income, name: '收入' },
          { value: chartData.value.total.outcome, name: '支出' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  totalChartInstance.value.setOption(option)
}

const initIncomeWayChart = () => {
  if (!incomeWayChartRef.value) return

  if (incomeWayChartInstance.value) {
    incomeWayChartInstance.value.dispose()
  }

  incomeWayChartInstance.value = echarts.init(incomeWayChartRef.value)

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: chartData.value.incomeWay.map(item => item.name === '1' ? '微信' : '支付宝')
    },
    series: [
      {
        name: '收入方式',
        type: 'pie',
        radius: '50%',
        data: chartData.value.incomeWay.map(item => ({
          value: item.amount,
          name: item.name === '1' ? '微信' : '支付宝'
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  incomeWayChartInstance.value.setOption(option)
}

const initOutcomeWayChart = () => {
  if (!outcomeWayChartRef.value) return

  if (outcomeWayChartInstance.value) {
    outcomeWayChartInstance.value.dispose()
  }

  outcomeWayChartInstance.value = echarts.init(outcomeWayChartRef.value)

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: chartData.value.outcomeWay.map(item => item.name === '1' ? '微信' : '支付宝')
    },
    series: [
      {
        name: '支出方式',
        type: 'pie',
        radius: '50%',
        data: chartData.value.outcomeWay.map(item => ({
          value: item.amount,
          name: item.name === '1' ? '微信' : '支付宝'
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  outcomeWayChartInstance.value.setOption(option)
}

const initOutcomeCategoryChart = () => {
  if (!outcomeCategoryChartRef.value) return

  if (outcomeCategoryChartInstance.value) {
    outcomeCategoryChartInstance.value.dispose()
  }

  outcomeCategoryChartInstance.value = echarts.init(outcomeCategoryChartRef.value)

  const categoryMap = {
    '1': '生活',
    '2': '住房',
    '3': '教育',
    '4': '医疗',
    '5': '娱乐',
    '6': '还款',
    '7': '其他'
  }

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: chartData.value.outcomeCategory.map(item => categoryMap[item.name])
    },
    series: [
      {
        name: '支出分类',
        type: 'pie',
        radius: '50%',
        data: chartData.value.outcomeCategory.map(item => ({
          value: item.amount,
          name: categoryMap[item.name]
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  outcomeCategoryChartInstance.value.setOption(option)
}

const initIncomeCategoryChart = () => {
  if (!incomeCategoryChartRef.value) return

  if (incomeCategoryChartInstance.value) {
    incomeCategoryChartInstance.value.dispose()
  }

  incomeCategoryChartInstance.value = echarts.init(incomeCategoryChartRef.value)

  const categoryMap = {
    '1': '工资',
    '2': '投资',
    '3': '其他'
  }

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: chartData.value.incomeCategory.map(item => categoryMap[item.name])
    },
    series: [
      {
        name: '收入分类',
        type: 'pie',
        radius: '50%',
        data: chartData.value.incomeCategory.map(item => ({
          value: item.amount,
          name: categoryMap[item.name]
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  incomeCategoryChartInstance.value.setOption(option)
}

// 获取数据
const fetchChartData = async () => {
  try {
    loading.value = true
    const { data } = await homeShow(filters.value)
    if (data.code === 200) {
      chartData.value.total.income = data.data.incomeTotal
      chartData.value.total.outcome = data.data.outcomeTotal
      chartData.value.incomeWay = data.data.incomeWayList
      chartData.value.outcomeWay = data.data.outcomeWayList
      chartData.value.outcomeCategory = data.data.outcomeList
      chartData.value.incomeCategory = data.data.incomeList
      
      isEmptyData.value = chartData.value.total.income === 0 && chartData.value.total.outcome === 0

      // 确保 DOM 更新完成后再初始化图表
      await nextTick()
      
      if (!isEmptyData.value) {
        initTotalChart()
        initIncomeWayChart()
        initOutcomeWayChart()
        initOutcomeCategoryChart()
        initIncomeCategoryChart()
      }
    } else {
      ElMessage.error(data.message || '数据获取失败')
    }
  } catch (error) {
    console.error('请求失败:', error)
    ElMessage.error('请求失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 监听窗口变化，调整图表大小
const handleResize = () => {
  [totalChartInstance, incomeWayChartInstance, outcomeWayChartInstance, outcomeCategoryChartInstance, incomeCategoryChartInstance]
    .forEach(instance => {
      if (instance.value) {
        instance.value.resize()
      }
    })
}

onMounted(() => {
  checkLoginStatus()
  fetchChartData()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  [totalChartInstance, incomeWayChartInstance, outcomeWayChartInstance, outcomeCategoryChartInstance, incomeCategoryChartInstance]
    .forEach(instance => {
      if (instance.value) {
        instance.value.dispose()
      }
    })
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.chart-container {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

.section-title {
  color: #303133;
  margin-bottom: 16px;
  font-size: 18px;
  font-weight: 600;
}

.filters-container {
  background: #ffffff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.05);
  margin-bottom: 24px;
}

.filters-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  align-items: center;
}

.filter-item {
  width: 100%;
}

.filter-btn {
  width: 100%;
  background-color: #67C23A;
  border-color: #67C23A;
  transition: all 0.3s;
}

.filter-btn:hover {
  opacity: 0.9;
  transform: translateY(-1px);
}

.charts-wrapper {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
}

.chart-card {
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.05);
  overflow: hidden;
}

.chart-header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.chart-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-content {
  padding: 16px;
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-tips {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

@media (max-width: 768px) {
  .chart-container {
    padding: 12px;
  }
  
  .charts-wrapper {
    grid-template-columns: 1fr;
  }
  
  .chart-content {
    height: 200px;
  }
}
</style>